//  ParkView.swift
//  Demo3
//
//  Created by Bigboss on 2025/3/7.
//

import SwiftUI
import RealityKit
import ARKit

struct ParkView: View {
    @State private var showInfoPanel = false
    @State private var temperature: Double = 25.0
    @State private var humidity: Double = 60.0
    @State private var modelEntity: Entity?
    
    @State private var selectedEntityName: String = ""
    @State private var showEntityPanel = false
    @State private var entityScreenPosition: CGPoint = .zero
    
    @EnvironmentObject var appModel: AppModel
    @Environment(\.openImmersiveSpace) var openImmersiveSpace
    @Environment(\.dismissImmersiveSpace) var dismissImmersiveSpace
    
    var body: some View {
        ZStack {
            // 3D 模型视图
            RealityView { content in
                
                do {
                    // load 园区场景
                    let model = try await Entity.load(named: "park")
                    let modelScale: Float = 0.029
                    model.scale = SIMD3<Float>(modelScale, modelScale, modelScale)
                    model.position.y -= 0.3
                    model.position.z = 0.4
                    model.position.x -= 0.06

                    // 添加定向光源
                    let directionalLight = DirectionalLight()
                    directionalLight.light.intensity = 2500
                    directionalLight.look(at: [0, 0, 0], from: [1, 2, 2], relativeTo: nil)
                    content.add(directionalLight)
                    
                    model.generateCollisionShapes(recursive: true)
                    model.components.set(InputTargetComponent(allowedInputTypes: .indirect))
                    
                    self.modelEntity = model
                    content.add(model)
                    
                    rotateModel(axis: [0, 1, 0])
                    rotateModel10(axis: [1, 0, 0])

                } catch {
                    print("Error loading model: \(error)")
                }
            }
            .gesture(
                SpatialTapGesture()
                    .targetedToAnyEntity()
                    .onEnded { value in
                        print("🎯 点击事件触发")
                        print("   📛 实体名称: \(value.entity.name)")
                        print("   📍 实体位置: \(value.entity.position)")
                    }
            )
            
            // 新增告警面板
            // 修改后的告警面板布局
            VStack {
                WarningPanelView2()
                    .padding(.top, 140) // 加大顶部间距
                    .padding(.trailing, 250) // 添加右侧间距
                Spacer()
            }
            .frame(maxWidth: .infinity, alignment: .trailing) // 右对齐
            
            VStack {
//                                // 旋转控制按钮
//                                HStack(spacing: 20) {
//                                    RotationButton(axis: .x) { rotateModel(axis: [1, 0, 0]) }
//                                    RotationButton(axis: .y) { rotateModel(axis: [0, 1, 0]) }
//                                    RotationButton(axis: .z) { rotateModel(axis: [0, 0, 1]) }
//                                }
//                                .padding(.top, 40)
                
                
//                Spacer()
//                HStack {
//                    Spacer()
//                    immersiveSwitch
//                        .padding(.trailing, 20)
//                        .padding(.bottom, 200)
//                }
            }
        }
        .onAppear {  // 新增 onAppear
             appModel.isImmersiveActive = true  // 进入时自动打开开关
         }
        .onChange(of: appModel.isImmersiveActive) { _, newValue in
            Task {
                if newValue {
                    await openImmersiveSpace(id: appModel.immersiveSpaceID)
                } else {
                    await dismissImmersiveSpace()
                }
            }
        }
    }
    
    // 旋转方法
    private func rotateModel(axis: SIMD3<Float>) {
        guard let model = modelEntity else { return }
        let radians = -Float(90).degreesToRadians
        let rotation = simd_quatf(angle: radians, axis: axis.normalized)
        model.transform.rotation = rotation * model.transform.rotation
    }
    
    // 向前旋转方法
    private func rotateModel10(axis: SIMD3<Float>) {
        guard let model = modelEntity else { return }
        let radians = Float(10).degreesToRadians
        let rotation = simd_quatf(angle: radians, axis: axis.normalized)
        model.transform.rotation = rotation * model.transform.rotation
    }

    
    // 提取出的开关组件
    private var immersiveSwitch: some View {
        HStack(spacing: 10) {
            Text("Immersive")
                .font(.system(size: 16, weight: .medium))
            
            Toggle("", isOn: $appModel.isImmersiveActive)
                .toggleStyle(SwitchToggleStyle(tint: .blue))
                .labelsHidden()
                .scaleEffect(1.1)
        }
        .padding(12)
        .background(
            RoundedRectangle(cornerRadius: 16)
                .fill(Color.white.opacity(0.1))
        )
        .padding(.trailing, 20)
        .padding(.bottom, 30)
    }
}

// 视觉特效视图（用于背景模糊效果）
struct VisualEffectView: UIViewRepresentable {
    func makeUIView(context: Context) -> UIVisualEffectView {
        UIVisualEffectView(effect: UIBlurEffect(style: .systemThinMaterial))
    }
    
    func updateUIView(_ uiView: UIVisualEffectView, context: Context) {}
}


